﻿using System;
using System.Web;
using Castle.Windsor;
using CommonServiceLocator.WindsorAdapter;
using Microsoft.Practices.ServiceLocation;
using Sok.Munkae.ApplicationServices;
using Sok.Munkae.ApplicationServices.DTO;
using Sok.Munkae.ApplicationServices.Membership;
using Sok.Munkae.Web.CastleWindsor;

namespace Sok.Munkae.Web
{
    public class Global : HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
        }

        protected void Session_Start(object sender, EventArgs e)
        {
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Or...you could stuff this part into an HttpModule 
            ServiceLocatorInitializer.Current()
                .InitializeOnce(
                () => InitializeServiceLocator());
            
            //TenantInitializer.Current.InitializeOnce(hostName);
            //AutoMapperInitializer.Current.InitializeOnce();
            //TODO: Hande errors here
        }

        protected virtual void InitializeServiceLocator()
        {
            InitializeAutoMapper();

            IWindsorContainer container = new WindsorContainer();
            ComponentRegistrar.AddComponentsTo(container);
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }

        private void InitializeAutoMapper()
        {
            DtoMaps.Init();
        }


        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var currentPrincipal = HttpContext.Current.User;
            if(currentPrincipal != null && currentPrincipal.Identity != null && currentPrincipal.Identity.IsAuthenticated)
            {
                var authenticationService = ServiceLocator.Current.GetInstance<IAuthenticationService>();
                var userContext = ServiceLocator.Current.GetInstance<IUserContext>();
                var user = authenticationService.GetAuthenticatedUser(currentPrincipal);
                userContext.SetUser(user);
            }

        }

        protected void Application_Error(object sender, EventArgs e)
        {
        }

        protected void Session_End(object sender, EventArgs e)
        {
        }

        protected void Application_End(object sender, EventArgs e)
        {
        }
    }
    

}